package com.mengye.socket.aes;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * **********************
 * * Author: Txz        *
 * * Date: 2023-04-20   *
 * * Time: 14:19        *
 * * to: xm             *
 * **********************
 **/
@Component
@Slf4j
public class AESUtils {

    private static String key;

    @Value("${aes.key}")
    public void setKsy(String key) {
        AESUtils.key = key;
    }

    private static String iv;

    @Value("${aes.iv}")
    public void setIv(String iv) {
        AESUtils.iv = iv;
    }

    // 是否启用aes
    public static Boolean isEnable;
    @Value("${aes.isEnable:true}")
    public void setIsEnable(Boolean isEnable) {
        AESUtils.isEnable = isEnable;
    }

    public static String encrypt(String plaintext) throws Exception {
        return isEnable ? encrypt(key, iv, plaintext) : plaintext;
    }

    /**
     * aes+base64 加密
     */
    public static String encrypt(String keyPara, String ivPara, String plaintext) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec key = new SecretKeySpec(keyPara.getBytes(), "AES");
        IvParameterSpec iv = new IvParameterSpec(ivPara.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
        byte[] encrypted = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encrypted);
    }

    public static String decrypt(String encryptedData) throws Exception {
        return decrypt(key, iv, encryptedData);
    }

    /**
     * aes+base64 解密
     */
    public static String decrypt(String keyPara, String ivPara, String encryptedData) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec key = new SecretKeySpec(keyPara.getBytes(), "AES");
        IvParameterSpec iv = new IvParameterSpec(ivPara.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(original, StandardCharsets.UTF_8);
    }

}
